/*
 * Copyright (C), 2002-2016, 上海亦寻信息技术有限公司
 * FileName: SubscribeServiceImp.java
 * Author:   linyao
 * Date:     2016-7-8 下午2:42:24
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.emm.yixun.website.service.customer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.activiti.engine.task.Comment;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.common.model.BusinessChange;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerComponentDto;
import com.emm.yixun.common.model.dto.SubscribeDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.AuditStatusEnum;
import com.emm.yixun.common.model.enums.IntentionLevelEnum;
import com.emm.yixun.common.model.enums.SexEnum;
import com.emm.yixun.common.model.enums.SubscribeBusinessStatusEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.vo.process.HistoryTaskInfoVo;

/**
 * 〈一句话功能简述〉 〈功能详细描述〉
 * 
 * @author linyao
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class SubscribeServiceImp implements SubscribeService {
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private TaskService taskService;
	
	 @Autowired
	 private UserServiceFacade userServiceFacade;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.emm.yixun.website.service.customer.SubscribeService#getSubscribeList(com.emm.yixun.common.model.dto.SubscribeDto
	 * , java.lang.Integer, java.lang.Integer)
	 */
	@Override
	public Response<Page<SubscribeDto>> getSubscribeList(SubscribeDto reqDto, Integer pageSize, Integer pageNum) {
		Response<Page<SubscribeDto>> depositListResDto = subscribeServiceFacade.getSubscribeList(reqDto, pageSize,
				pageNum);

		if (reqDto.getCustomerId() != null && depositListResDto.isSuccess() && depositListResDto.getEntity() != null
				&& depositListResDto.getEntity().getRows() != null
				&& depositListResDto.getEntity().getRows().size() > 0) {// 查询审批历史记录
			List<SubscribeDto> list = depositListResDto.getEntity().getRows();
			for (SubscribeDto subscribeDto : list) {
				if (subscribeDto.getProcInstId() != null) {
					List<HistoricActivityInstance> instances = historyService.createHistoricActivityInstanceQuery()
							.processInstanceId(subscribeDto.getProcInstId()).orderByHistoricActivityInstanceStartTime()
							.desc().list();
					if (instances != null && instances.size() > 0) {
						List<HistoryTaskInfoVo> userTaskList = new ArrayList<HistoryTaskInfoVo>();
						boolean isEnd = true;
						for (HistoricActivityInstance historicActivityInstance : instances) {
							if (historicActivityInstance.getEndTime() != null) {// 过滤未审批的数据
								HistoryTaskInfoVo htf = new HistoryTaskInfoVo();

								if (historicActivityInstance.getActivityType().equals("startEvent")) {// 开始节点
									ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
											.createProcessInstanceHistoryLogQuery(
													historicActivityInstance.getProcessInstanceId()).singleResult();
									htf.setTaskName("启动");
									UserDto ud=new UserDto();
									ud.setUserAccount(processInstanceHistoryLog.getStartUserId());
									ResponseList<User> userList=userServiceFacade.findByDto(ud);
									if(userList.isSuccess() && null!=userList.getEntity()){
										htf.setTaskUserName(userList.getEntity().get(0).getUserName());
									}
									htf.setTaskCheckStatus("发起");
									htf.setStartDate(historicActivityInstance.getStartTime());
									htf.setEndDate(historicActivityInstance.getEndTime());

									userTaskList.add(htf);
									continue;
								}

								if (historicActivityInstance.getActivityType().equals("endEvent")) {// 结束节点
									continue;
								}

								List<Comment> commentList = taskService.getTaskComments(historicActivityInstance
										.getTaskId());
								htf.setTaskName(historicActivityInstance.getActivityName());
								htf.setStartDate(historicActivityInstance.getStartTime());
								htf.setEndDate(historicActivityInstance.getEndTime());
								if (isEnd)// 为最后一个审批节点
									htf.setIsEnd(isEnd);
								if (null != commentList && commentList.size() > 0){
									String userAccount=commentList.get(0).getUserId();
									UserDto ud=new UserDto();
									ud.setUserAccount(userAccount);
									ResponseList<User> userList=userServiceFacade.findByDto(ud);
									if(userList.isSuccess() && null!=userList.getEntity()){
										htf.setTaskUserName(userList.getEntity().get(0).getUserName());
									}
									
								}

								userTaskList.add(htf);

								isEnd = false;
							}
						}

						if (userTaskList.size() > 0) {
							for (HistoryTaskInfoVo historyTaskInfoVo : userTaskList) {
								if (historyTaskInfoVo.getTaskName().equals("启动")) {// 获取提交时间
									subscribeDto.setSmTartTime(historyTaskInfoVo.getStartDate());
								}
								if (historyTaskInfoVo.getIsEnd() != null && historyTaskInfoVo.getIsEnd()) {// 获取最后的审批人与审核时间
									subscribeDto.setTaskUserName(historyTaskInfoVo.getTaskUserName());
									subscribeDto.setCkEndTime(historyTaskInfoVo.getEndDate());
								}
							}
						}
					}
				}

			}

		}

		return depositListResDto;
	}

	@Override
	public List<SubscribeDto> getSubscribeExportList(SubscribeDto reqDto) {
		ResponseList<SubscribeDto> responseList = subscribeServiceFacade.querySubscribeExport(reqDto);
		return responseList.getEntity();
	}

	@Override
	public List<Map<String, String>> returnFieldSubscribe(List<SubscribeDto> list,String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		for (int i=0;i<list.size();i++) {
			SubscribeDto subscribe = list.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(head[0]+"_"+i,DateUtils.DateToString(subscribe.getSubscribeDate(), DateStyle.YYYY_MM_DD.getValue())); //认购日期
			map.put(head[1]+"_"+i, subscribe.getCustomerName());//客户姓名
			map.put(head[2]+"_"+i, subscribe.getCombinedName()); //房号
			map.put(head[3]+"_"+i, subscribe.getHouseTypeName()); //户型
			map.put(head[4]+"_"+i, subscribe.getCalculateArea()==null?"":subscribe.getCalculateArea().toString()); //计价面积
			map.put(head[5]+"_"+i, subscribe.getSubscribePrice()==null?"":subscribe.getSubscribePrice().toString()); //签约单价
			map.put(head[6]+"_"+i, subscribe.getSubscribeAmount()==null?"":subscribe.getSubscribeAmount().toString());//合同金额
			map.put(head[7]+"_"+i, DateUtils.DateToString(subscribe.getConversionSignDate(), DateStyle.YYYY_MM_DD.getValue()));//转签约日期
			String overDueDay =  subscribe.getOverdueDay();
			Integer overDue =  null;
			if(!StringUtils.isEmpty(overDueDay)){
				overDue = new Integer(overDueDay);
				if(overDue>0){
					overDueDay="是";
				}else{
					overDueDay = "否";
				}
			}
			map.put(head[8]+"_"+i, overDueDay);//是否逾期未转签约
			map.put(head[9]+"_"+i, overDue==null||overDue==0?"":overDue.toString()); //逾期天数
			map.put(head[10]+"_"+i, subscribe.getDepositReceivable()==null?"":subscribe.getDepositReceivable().toString()); //认购金
			map.put(head[11]+"_"+i, subscribe.getTotalRealAmount()==null?"":subscribe.getTotalRealAmount().toString()); //已收认购金
			map.put(head[12]+"_"+i, subscribe.getUserName()); //经纪人
			map.put(head[13]+"_"+i, subscribe.getBusinessStatus()==null?"":SubscribeBusinessStatusEnum.getByNo(subscribe.getBusinessStatus()).getDes());
			map.put(head[14]+"_"+i, subscribe.getAuditStatus()==null?"":AuditStatusEnum.getByNo(subscribe.getAuditStatus()).getDes());
			listMap.add(map);
		}
		return listMap;
	}

	@Override
	public List<Map<String, String>> businessChangeExport(List<BusinessChange> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		for (int i=0;i<list.size();i++) {
			BusinessChange businessChange = list.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(head[0]+"_"+i,DateUtils.DateToString(businessChange.getDidTime(), DateStyle.YYYY_MM_DD.getValue())); 
			map.put(head[1]+"_"+i,DateUtils.DateToString(businessChange.getCheckDate(), DateStyle.YYYY_MM_DD.getValue())); 
			map.put(head[2]+"_"+i, businessChange.getCustomerName());
			map.put(head[3]+"_"+i, businessChange.getCustomerPhone());
			map.put(head[4]+"_"+i, businessChange.getCombinedName());
			map.put(head[5]+"_"+i, businessChange.getHouseTypeName());
			map.put(head[6]+"_"+i, businessChange.getCalculateArea() == null?"":businessChange.getCalculateArea().toString());
			map.put(head[7]+"_"+i, businessChange.getSubscribeAmount() == null?"":businessChange.getSubscribeAmount().toString());
			map.put(head[8]+"_"+i, businessChange.getReceived() == null?"":businessChange.getReceived().toString());
			map.put(head[9]+"_"+i, businessChange.getRetired() == null?"":businessChange.getRetired().toString());
			map.put(head[10]+"_"+i, businessChange.getUserName());
			map.put(head[11]+"_"+i, businessChange.getBusinessStatus());
			map.put(head[12]+"_"+i, businessChange.getAuditStatus());
			listMap.add(map);
		}
		return listMap;
	}

	@Override
	public List<Map<String, String>> giveUpCustomerExport(List<CustomerComponentDto> list, String[] head) {
		List<Map<String, String>> listMap = new ArrayList<Map<String,String>>();
		for (int i = 0; i < list.size(); i++) {
			CustomerComponentDto customer = list.get(i);
			Map<String, String> map = new HashMap<String, String>();
			map.put(head[0]+"_"+i, StringUtils.isEmpty(customer.getCustomerName())?"":customer.getCustomerName());
			map.put(head[1]+"_"+i, customer.getCustomerPhone());
			map.put(head[2]+"_"+i, StringUtils.isEmpty(customer.getCustomerSex())?"":customer.getCustomerSex());
			map.put(head[3]+"_"+i, customer.getProjectName());
			map.put(head[4]+"_"+i, IntentionLevelEnum.getByNo(customer.getIntentionLevel()).getDes());
			map.put(head[5]+"_"+i, customer.getUserName());
			map.put(head[6]+"_"+i, StringUtils.isEmpty(customer.getFtContactWay())?"无":customer.getFtContactWay()); //首次接触方式
			map.put(head[7]+"_"+i, DateUtils.DateToString(customer.getCreateTime(), DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
			map.put(head[8]+"_"+i, DateUtils.DateToString(customer.getLastFollowTime(), DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
			map.put(head[9]+"_"+i, DateUtils.DateToString(customer.getResignTime(), DateStyle.YYYY_MM_DD_HH_MM_SS.getValue()));
			listMap.add(map);
		}
		return listMap;
	}

}
